package database

import (
	"demo/models"
	"errors"
	"time"

	"github.com/sirupsen/logrus"
)

// 插入电费账单
func InsertElectricityBill(bill *models.ElectricityBills) error {
	// 更新 EleInfo 表
	eleInfo := &models.EleInfo{}
	exists, err := engine.Where("id = ?", bill.UserId).Get(eleInfo)
	if err != nil {
		logrus.Error("failed to query user ele info: ", err)
		return err
	}
	if !exists {
		// 创建新的 EleInfo 记录
		eleInfo = &models.EleInfo{
			Id:          bill.UserId,
			EleSum:      bill.Amount,
			EleStatus:   "欠费",
			EleBalance:  0,
			// EleUsemoney: bill.Amount,
		}
		_, err = engine.Insert(eleInfo)
		if err != nil {
			logrus.Error("failed to insert user ele info: ", err)
			return err
		}
	} else {
		// 更新已有的 EleInfo 记录
		eleInfo.EleSum += bill.Amount
		eleInfo.EleUsemoney += bill.Amount
		eleInfo.EleStatus = "欠费"
		_, err = engine.Where("id = ?", eleInfo.Id).Update(eleInfo)
		if err != nil {
			logrus.Error("failed to update user ele info: ", err)
			return err
		}
	}
	// 插入电费账单
	_, err = engine.Insert(bill)
	if err != nil {
		logrus.Error("failed to insert electricity bill: ", err)
		return err
	}
	return nil
}

// 根据用户ID查询电费账单
func GetElectricityBillsByUserId(userId int) ([]models.ElectricityBills, error) {
	var bills []models.ElectricityBills
	err := engine.Where("user_id = ?", userId).Find(&bills)
	if err != nil {
		logrus.Error("failed to query electricity bills: ", err)
		return nil, err
	}
	if len(bills) == 0 {
		return nil, errors.New("no bills found for the user")
	}
	return bills, nil
}


// 缴纳电费账单
func PayElectricityBill(userId, billId int, amount float32, paymentMethod string) (models.Payments, error) {
	var bill models.ElectricityBills
	exists, err := engine.Where("id = ? AND user_id = ?", billId, userId).Get(&bill)
	if err != nil {
		logrus.Error("failed to query electricity bill: ", err)
		return models.Payments{}, err
	}
	if !exists {
		return models.Payments{}, errors.New("bill not found")
	}
	if bill.Status == "paid" {
		return models.Payments{}, errors.New("bill already paid")
	}

	// 更新账单状态和支付信息
	bill.ElePayment = amount
	// bill.EleBalanceNow = amount
	bill.PayTime = time.Now()
	bill.Status = "paid"

	_, err = engine.Where("id = ?", bill.Id).Update(&bill)
	if err != nil {
		logrus.Error("failed to update electricity bill: ", err)
		return models.Payments{}, err
	}

	// 更新 EleInfo 表
	eleInfo := &models.EleInfo{}
	exists, err = engine.Where("id = ?", userId).Get(eleInfo)
	if err != nil {
		logrus.Error("failed to query user ele info: ", err)
		return models.Payments{}, err
	}
	if !exists {
		return models.Payments{}, errors.New("no user ele info found")
	}
	eleInfo.EleSum=0
	eleInfo.EleStatus="正常"
	_, err = engine.Where("id = ?", eleInfo.Id).Update(eleInfo)
	if err != nil {
		logrus.Error("failed to update user ele info: ", err)
		return models.Payments{}, err
	}

	// 记录支付信息
	payment := models.Payments{
		UserId:        userId,
		BillId:        billId,
		Amount:        amount,
		PaymentMethod: paymentMethod,
		PaymentDate:   time.Now(),
	}
	_, err = engine.Insert(&payment)
	if err != nil {
		logrus.Error("failed to insert payment record: ", err)
		return models.Payments{}, err
	}
	return payment, nil
}

//将账单通知插入到Notifications表
func InsertOneNotice(notice *models.Notifications) error {
	_, err := engine.InsertOne(notice)
	if err != nil {
		logrus.Error("failed to insert notification: ", err)
		return err
	}
	return err
}


func InsertOneUsageReport(report *models.UsageReports) error {
	_, err := engine.InsertOne(report)
	if err != nil {
		logrus.Error("failed to insert usageReporTable: ", err)
		return err
	}
	return err
}


//获取所有用户账单
func GetAllBills() ([]models.ElectricityBills, error) {
	var bills []models.ElectricityBills
	err := engine.Find(&bills)
	if err != nil {
		logrus.Error("failed to query all electricity bill: ", err)
		return nil, err
	}
	return bills, nil
}

//获取所有用支付信息
func GetAllPayments() ([]models.Payments, error) {
	var payments []models.Payments
	err := engine.Find(&payments)
	if err != nil {
		logrus.Error("failed to query all payment: ", err)
		return nil, err
	}
	return payments, nil
}

